﻿using Microsoft.VisualBasic;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Shuba.Web
{
    public class LoginAttemptManager
    {
        public static void userLoginFailed(string user)
        {
            int usernya = 0;
            string datetimenya = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

            if (HttpContext.Current.Session[user] != null)
            {
                usernya = Convert.ToInt32(HttpContext.Current.Session[user]);
                long minutes = DateAndTime.DateDiff("n", Convert.ToDateTime(HttpContext.Current.Session[user + "_time"]), DateTime.Now,
                    Microsoft.VisualBasic.FirstDayOfWeek.Sunday, FirstWeekOfYear.Jan1);
                if (minutes >= getLoginAttemptMinutes())
                    usernya--;
            }

            usernya++;
            HttpContext.Current.Session[user] = usernya;
            HttpContext.Current.Session[user + "_time"] = datetimenya;
        }

        public static bool userAbleToLogin(string user, login l)
        {
            if (HttpContext.Current.Session[user] != null
                && Convert.ToInt32(HttpContext.Current.Session[user]) == getLoginAttemptMax())
            {
                long minutes = DateAndTime.DateDiff("n", Convert.ToDateTime(HttpContext.Current.Session[user + "_time"]), DateTime.Now,
                    Microsoft.VisualBasic.FirstDayOfWeek.Sunday, FirstWeekOfYear.Jan1);
                if (minutes < getLoginAttemptMinutes())
                    return false;
            }
            return true;
        }

        public static long getLoginAttemptMinutes()
        {
            Shuba.Framework.ConfigHelper _ConfigHelper = Shuba.Framework.ConfigHelper.GetInstance;
            string min = _ConfigHelper.GetAppSettingValue("loginAttemptMinutes");
            if (min == null) return 15;
            return Convert.ToInt64(min);
        }

        public static int getLoginAttemptMax()
        {
            Shuba.Framework.ConfigHelper _ConfigHelper = Shuba.Framework.ConfigHelper.GetInstance;
            string min = _ConfigHelper.GetAppSettingValue("loginAttemptMax");
            if (min == null) return 3;
            return Convert.ToInt32(min);
        }
    }
}
